#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from sqlalchemy import Column, String, create_engine, DateTime, Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime
import random
import string


Base = declarative_base()


class Gupiao(Base):

    __tablename__ = 'gupiao'

    id = Column(Integer, primary_key=True)
    name = Column(String(20))
    price = Column(String(10))
    date = Column(DateTime, default=datetime.now())


def get_session():
    engine = create_engine('mysql+pymysql://tim:Tim123@localhost:3306/gupiao?charset=utf8') # noqa

    Base.metadata.create_all(engine)  # 创建表，如果存在就忽略

    DBSession = sessionmaker(bind=engine)
    return DBSession()


if __name__ == '__main__':

    name = ''.join(random.sample(string.ascii_letters + string.digits, 5))
    price = str(random.randrange(1, 100))

    session = get_session()
    try:
        _id = session.query(Gupiao).all()[-1]
    except Exception:
        new_id = 1
    else:
        new_id = _id.id + 1

    instance = Gupiao(id=new_id, name=name, price=price)
    session.add(instance)

    session.commit()
